﻿//#define OverloadDelete
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MvcApplication2.Models;
using System.IO;

namespace MvcApplication2.Controllers
{
    public class RecipesController : Controller
    {
        private BaseDBContext db = new BaseDBContext();



        // GET: /Recipes/SearchIndex
#if ONE
public ActionResult SearchIndex(string Genre, string searchString)
{

    var GenreLst = new List<string>();
    GenreLst.Add("All");

    var GenreQry = from d in db.Recipes
                   orderby d.title
                   select d.title;
    GenreLst.AddRange(GenreQry.Distinct());
    ViewBag.Genre = new SelectList(GenreLst);

    var recipes = from m in db.Recipes
                 select m;

    if (!String.IsNullOrEmpty(searchString))
    {
        recipes = recipes.Where(s => s.title.Contains(searchString));
    }

    if (string.IsNullOrEmpty(Genre) || Genre == "All")
        return View(recipes);
    else
    {
        return View(recipes.Where(x => x.Genre == Genre));
    }

}
#else

        public ActionResult SearchIndex(string category, string searchString, string userSearch)
        {
            var categories = (from b in db.Categories select b).ToList();
            ViewBag.category = new SelectList(categories, "CategoryID", "Name");

            var recipes = from m in db.Recipes
                         select m;

            if (!String.IsNullOrEmpty(searchString))
            {
                recipes = recipes.Where(s => s.Title.Contains(searchString));
            }

            if (!String.IsNullOrEmpty(userSearch))
            {
                recipes = recipes.Where(s => s.User.Login.Contains(userSearch));
            }


            if (string.IsNullOrEmpty(category))
                return View(recipes);
            else
            {
                int categoryInt = int.Parse(category);
                return View(recipes.Where(x => x.Category.CategoryID == categoryInt));
            }

        }
#endif



        //public ActionResult SearchIndex(string searchString)
        //{          
        //    var recipes = from m in db.recipes
        //                 select m;

        //    if (!String.IsNullOrEmpty(searchString))
        //    {
        //        recipes = recipes.Where(s => s.Title.Contains(searchString));
        //    }

        //    return View(recipes);
        //}





        [HttpPost]
        public string SearchIndex(FormCollection fc, string searchString)
        {
            return "<h3> From [HttpPost]SearchIndex: " + searchString + "</h3>";
        }

        //
        // GET: /Recipes/Books
        public ActionResult Books(string searchString, string userSearch)
        {
            var books = from m in db.CookBooks
                          select m;

            if (!String.IsNullOrEmpty(searchString))
            {
                books = books.Where(s => s.Name.Contains(searchString));
            }

            if (!String.IsNullOrEmpty(userSearch))
            {
                books = books.Where(s => s.User.Login.Contains(userSearch));
            }

            return View(books);
        }


        //
        // GET: /Recipes/BCreate
        public ActionResult BCreate()
        {
            if (Session["LoggedId"] == null)
                return RedirectToAction("Error", "Home");

            return View();
        }

        //
        // POST: /Recipes/BCreate

        [HttpPost]
        public ActionResult BCreate(CookBook cookbook)
        {
            if (Session["LoggedId"] == null)
                return RedirectToAction("Error", "Home");

            cookbook.UserID = (int)Session["LoggedId"];

            if (ModelState.IsValid)
            {
                db.CookBooks.Add(cookbook);
                db.SaveChanges();
                return RedirectToAction("Books");
            }
            return View(cookbook);
        }

        //
        // POST: /Recipes/BBCreate

        public ActionResult BBCreate(string category, string searchString, string userSearch, int id = 0, int ide = 0)
        {
            CookBook cookbook = db.CookBooks.Find(id);
            ViewBag.cookbookname = cookbook.Name;
            ViewBag.cookbookid = cookbook.CookBookID;

            if (Session["LoggedId"] == null)
                return RedirectToAction("Error", "Home");
            if (!(bool)Session["LoggedAdmin"])
                if (cookbook.UserID != (int)Session["LoggedId"])
                    return RedirectToAction("Error", "Home");

            // tutaj dodawanie tego przepisu do ksiazki
            if (ide > 0)
            {
                CookBookRecipe cookbookrecipe = new CookBookRecipe();
                cookbookrecipe.CookBookID = cookbook.CookBookID;
                cookbookrecipe.RecipeID = ide;
                db.CookBookRecipes.Add(cookbookrecipe);
                db.SaveChanges();
            }

            var categories = (from b in db.Categories select b).ToList();
            ViewBag.category = new SelectList(categories, "CategoryID", "Name");

            var recipes = from m in db.Recipes
                          select m;
            var recipes2 = from m in db.Recipes
                          select m;
            var cookrecipes = from m in db.CookBookRecipes
                              select m;

            int tmphelp = cookbook.CookBookID;
            recipes2 = recipes2.Where(s => s.CookBookRecipes.Contains(cookrecipes.Where(r => r.RecipeID == s.RecipeID & r.CookBookID == tmphelp).FirstOrDefault()));
            recipes = recipes.Except(recipes2);


            if (!String.IsNullOrEmpty(searchString))
            {
                recipes = recipes.Where(s => s.Title.Contains(searchString));
            }

            if (!String.IsNullOrEmpty(userSearch))
            {
                recipes = recipes.Where(s => s.User.Login.Contains(userSearch));
            }


            if (string.IsNullOrEmpty(category))
                return View(recipes);
            else
            {
                int categoryInt = int.Parse(category);
                return View(recipes.Where(x => x.Category.CategoryID == categoryInt));
            }

        }

        //
        // GET: /Recipes/BDetails

        public ActionResult BDetails(int id = 0)
        {
            CookBook cookbook = db.CookBooks.Find(id);
            if (cookbook == null)
            {
                return HttpNotFound();
            }
            if (Session["LoggedId"] == null || cookbook.User.UserID != (int)Session["LoggedId"])
                ViewBag.isOwner = false;
            else ViewBag.isOwner = true;

            ViewBag.thisBook = id;
            ViewBag.cookbookname = cookbook.Name;
            ViewBag.cookbookdescription = cookbook.Description;

            var recipes = from m in db.CookBookRecipes
                        select m;

            recipes = recipes.Where(s => s.CookBookID == cookbook.CookBookID);

            return View(recipes);
        }

        //
        // GET: /Recipes/BDelete
        public ActionResult BDelete(int id = 0)
        {
            CookBook cookbook = db.CookBooks.Find(id);
            if (cookbook == null)
            {
                return HttpNotFound();
            }
            if (Session["LoggedId"] == null)
                return RedirectToAction("Error", "Home");
            if (!(bool)Session["LoggedAdmin"])
                if (cookbook.UserID != (int)Session["LoggedId"])
                    return RedirectToAction("Error", "Home");

            db.CookBooks.Remove(cookbook);
            db.SaveChanges();
            return RedirectToAction("Books");
        }

        //
        // GET: /Recipes/BBDelete
        public ActionResult BBDelete(int id = 0, int idb = 0)
        {
            CookBookRecipe cookbook = db.CookBookRecipes.Find(id);
            if (cookbook == null)
            {
                return HttpNotFound();
            }
            if (Session["LoggedId"] == null)
                return RedirectToAction("Error", "Home");
            if (!(bool)Session["LoggedAdmin"])
                if (cookbook.CookBook.UserID != (int)Session["LoggedId"])
                    return RedirectToAction("Error", "Home");
            db.CookBookRecipes.Remove(cookbook);
            db.SaveChanges();
            if (idb == 0)
                return RedirectToAction("Books");

            return RedirectToAction("BDetails", new { id = idb });
        }


        //
        // GET: /Recipes/

        public ViewResult Index()
        {
            return View(db.Recipes.ToList());
        }

        //
        // GET: /Recipes/My
        public ActionResult My()
        {
            if (Session["LoggedId"] == null)
                return Redirect("Index");
            //User user = db.Users.Find((int)Session["LoggedId"]);
            var recipes = from m in db.Recipes
                          select m;
            int baba = (int)Session["LoggedId"];
            return View(recipes.Where(s => s.UserID == baba).ToList());
        }


        //
        // GET: /Recipes/Details/5

        public ActionResult Details(int id = 0)
        {
            Recipe recipe = db.Recipes.Find(id);
            if (recipe == null)
            {
                return HttpNotFound();
            }
            ViewBag.likes = db.Votes.Where(m => m.Like == true && m.RecipeID == id).Count();
            ViewBag.all = db.Votes.Where(m => m.RecipeID == id).Count();
            if (ViewBag.all == 0)
            {
                ViewBag.percent = 0;
            }
            else
            {
                ViewBag.percent = ViewBag.likes * 100.0 / ViewBag.all;
            }

            return View(recipe);
        }

        //
        // GET: /Recipes/Create


        public ActionResult Create()
        {
            if (Session["LoggedId"] == null)
                return RedirectToAction("Error", "Home");
            var categories = (from b in db.Categories select b).ToList();
            ViewBag.category1 = new SelectList(categories, "CategoryID", "Name");

            return View();
        }




        public string AddSomeCategory()
        {
            Category cat = new Category();
            cat.Name = "Pikantne";
            cat.Description = "Danie pikantne, dla koneserów ostrych smaków.";
            db.Categories.Add(cat);
            db.SaveChanges();


            cat = new Category();
            cat.Name = "Deser";
            cat.Description = "Słodkie rozkosze dla podniebienia.";
            db.Categories.Add(cat);
            db.SaveChanges();

            cat = new Category();
            cat.Name = "Przystawka";
            cat.Description = "Przystawka do doskonały sposób na wprowadzenie do głównego dania.";
            db.Categories.Add(cat);
            db.SaveChanges();

            User admin = new User();
            admin.Admin = true;
            admin.Blocked = false;
            admin.Login = "admin";
            admin.Password = "admin";

            db.Users.Add(admin);
            db.SaveChanges();

            return "oklie doklie";
        }


        //
        // POST: /Recipes/Create

        [HttpPost]
        public ActionResult Create(Recipe recipe, string category1, HttpPostedFileBase ImagePath)
        {
            if (Session["LoggedId"] == null)
                return RedirectToAction("Error", "Home");
				

            recipe.CategoryID = int.Parse(category1);
            recipe.UserID = (int)Session["LoggedId"];

            if (ModelState.IsValid)
            {
                if (ImagePath != null && ImagePath.ContentLength > 0)
                {
                    var fileName = recipe.RecipeID + Path.GetFileName(ImagePath.FileName);
                    var path = Path.Combine(Server.MapPath("~/uploads"), fileName);
                    ImagePath.SaveAs(path);
                    recipe.ImagePath = fileName;
                }
                else
                {
                    recipe.ImagePath = null;
                }

                db.Recipes.Add(recipe);
                db.SaveChanges();
                return RedirectToAction("My", "Recipes");
            }

            var categories = (from b in db.Categories select b).ToList();
            ViewBag.category1 = new SelectList(categories, "CategoryID", "Name");

            return View(recipe);
        }

        //
        // GET: /Recipes/Edit/5

        public ActionResult Edit(int id = 0)
        {
            Recipe recipe = db.Recipes.Find(id);
            if (recipe == null)
            {
                return HttpNotFound();
            }
            if (Session["LoggedId"] == null)
                return RedirectToAction("Error", "Home");
            if (!(bool)Session["LoggedAdmin"])
                if (recipe.UserID != (int)Session["LoggedId"])
                    return RedirectToAction("Error", "Home");

            var categories = (from b in db.Categories select b).ToList();
            ViewBag.category1 = new SelectList(categories, "CategoryID", "Name");

            return View(recipe);
        }

        //
        // POST: /Recipes/Edit/5

        [HttpPost]
        public ActionResult Edit(Recipe recipe, string category1, HttpPostedFileBase ImagePath)
        {
            recipe.CategoryID = int.Parse(category1);

            if (Session["LoggedId"] == null)
                return RedirectToAction("Error", "Home");
            if (!(bool)Session["LoggedAdmin"])
                if (recipe.UserID != (int)Session["LoggedId"])
                    return RedirectToAction("Error", "Home");

            if (ModelState.IsValid)
            {
                if (ImagePath != null && ImagePath.ContentLength > 0)
                {
                    var fileName = recipe.RecipeID + Path.GetFileName(ImagePath.FileName);
                    var path = Path.Combine(Server.MapPath("~/uploads"), fileName);
                    ImagePath.SaveAs(path);
                    recipe.ImagePath = fileName;
                }

                db.Entry(recipe).State = EntityState.Modified;
                db.SaveChanges();
                return RedirectToAction("My", "Recipes");
            }
            return View(recipe);
        }

        //
        // GET: /Recipes/Delete/5

        public ActionResult Delete(int id = 0)
        {
            Recipe recipe = db.Recipes.Find(id);
            if (recipe == null)
            {
                return HttpNotFound();
            }
            if (Session["LoggedId"] == null)
                return RedirectToAction("Error", "Home");
            if (!(bool)Session["LoggedAdmin"])
                if (recipe.UserID != (int)Session["LoggedId"])
                    return RedirectToAction("Error", "Home");
            
            return View(recipe);
        }
#if OverloadDelete
        public ActionResult Delete(FormCollection fcNotUsed, int id = 0)
        {
            Recipe recipe = db.Recipes.Find(id);
            if (recipe == null)
            {
                return HttpNotFound();
            }
            db.Recipes.Remove(recipe);
            db.SaveChanges();
            return RedirectToAction("Index");
        }
#else
        //
        // POST: /recipes/Delete/5

        [HttpPost, ActionName("Delete")]
        public ActionResult DeleteConfirmed(int id = 0)
        {
            Recipe recipe = db.Recipes.Find(id);
            if (recipe == null)
            {
                return HttpNotFound();
            }
            db.Recipes.Remove(recipe);
            db.SaveChanges();
            return RedirectToAction("Index");
        }
#endif





    }
}